/****************************************************
	文件：MotionBlur.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/8/14 14:3:58
	功能：运动模糊
*****************************************************/

using System;
using UnityEngine;

namespace RenderingPractice
{
    public class MotionBlur : PostEffectsBase
    {
        [Range(0.0f, 0.9f), Tooltip("运动模糊强度")]
        public float BlurAmount = 0.5f;
        public Shader MotionBlurShader;
        private Material mMotionBlurMat;

        public Material MotionBlurMat
        {
            get
            {
                mMotionBlurMat = CheckShaderAndCreateMaterial(MotionBlurShader, mMotionBlurMat);
                return mMotionBlurMat;
            }
        }

        /// <summary>
        /// 保存图片累加的结果
        /// </summary>
        private RenderTexture mAccumulationTexture;
        private void OnDisable()
        {
            DestroyImmediate(mAccumulationTexture);
        }

        private void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (MotionBlurMat != null)
            {
                //创建 RenderTexture
                if (mAccumulationTexture == null || mAccumulationTexture.width != source.width || mAccumulationTexture.height != source.height)
                {
                    DestroyImmediate(mAccumulationTexture);
                    mAccumulationTexture = new RenderTexture(source.width, source.height, 0);
                    mAccumulationTexture.hideFlags = HideFlags.HideAndDontSave;
                    Graphics.Blit(source, mAccumulationTexture);
                }
                mAccumulationTexture.MarkRestoreExpected(); //进行渲染纹理的恢复操作？
                MotionBlurMat.SetFloat("_BlurAmount", 1.0f - BlurAmount);
                Graphics.Blit(source, mAccumulationTexture, MotionBlurMat);
                Graphics.Blit(mAccumulationTexture, destination);
            }
            else
            {
                Graphics.Blit(source, destination);
            }
        }
    }
}
